import { Button, Checkbox, Form, Input, Col ,message} from 'antd'
import { useState, useContext } from 'react'
import { AppContext } from '@/store'
import { LoginApi } from '../apis'

const LoginForm = ({ switchHandle }) => {
  const { state, dispatch } = useContext(AppContext)

  const checkUsername = (_, value) => {
    if (value && /^\d+$/.test(value)) {
        console.log("----",value)
      return Promise.reject(new Error('用户名不能为纯数字'))
    }
    return Promise.resolve();
  };

  const onFinish = async (values) => {
    const result = await LoginApi(values)
    console.log('result:', result)
    if (result.success) {
      dispatch({ type: 'SET_VISIBLE', payload: false })
      dispatch({ type: 'SET_TOKEN', payload: result.token })
      dispatch({ type: 'SET_USER', payload: {username: values.username}})
      localStorage.setItem('token', result.token)
      localStorage.setItem('user', JSON.stringify({username: values.username}))
      if(state.messageList.length >1){
        window.location.href = "#/chat"
      }
    }else{
      message.error("帐号或者密码错误！")
    }
  }
  const onFinishFailed = () => {}
  return (
    <Col className="login-form-container">
      <Col className="login-form-title">
        <span>用户登录</span>
      </Col>
      <Form
        name="basic"
        // labelCol={{ span: 8 }}
        layout="vertical"
        style={{ maxWidth: 400, width: '100%' }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: '用户名不能为空!' },{ validator: checkUsername }]}
        >
          <Input placeholder="请输入用户名" style={{ height: '40px' }} />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '密码不能为空!' }]}
        >
          <Input.Password placeholder="请输入密码" style={{ height: '40px' }} />
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            block
            htmlType="submit"
            style={{ height: '40px' }}
          >
            开始使用
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            type="link"
            block
            style={{ height: '40px' }}
            onClick={() => switchHandle(0)}
          >
            还没有账号？点击注册
          </Button>
        </Form.Item>
      </Form>
    </Col>
  )
}

export default LoginForm
